

import com.book.constrains.SystemConstants;
import com.book.protocol.Protocol;
import task.AdminTaskThread;
import task.ReaderTaskThread;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ResourceBundle;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 图书管理系统服务器端
 */
public class BookServer {
    // 线程池对象
    private static ThreadPoolExecutor poolExecutor;
    // 服务监听端口
    private static int port;

    // 静态块，加载配置
    static {
        // 基于资源绑定类加载配置文件
        ResourceBundle bundle = ResourceBundle.getBundle("config");
        // 读取端口号
        port = Integer.parseInt(bundle.getString("server.port"));
    }

    // 服务器端以多线程方式处理多个客户端的交互
    public static void main(String[] args) throws IOException {
        // 创建线程池对象
        poolExecutor = new ThreadPoolExecutor(10, 100, 100, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(30), Executors.defaultThreadFactory());

        System.out.println("=== 图书管理系统启动 ===");
        System.out.println("服务器监听端口：" + port);
        ServerSocket serverSocket = new ServerSocket(port);

        // 循环以多线程方式处理多个客户端请求
        while (true) {
            try {
                // 监听阻塞，直到客户端连接到达
                Socket client = serverSocket.accept();

                // 构建对象输入流，接收客户端的操作需求
                ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
                Protocol<Object> protocol = (Protocol<Object>) ois.readObject();

                if (SystemConstants.TYPE_ADMIN.equalsIgnoreCase(protocol.getType())) {
                    // 管理员操作
                    System.out.println("欢迎管理员访问图书管理系统！");
                    System.out.println("您的IP地址是：" + client.getInetAddress().getHostAddress());

                    // 提交管理员线程任务到线程池来执行
                    poolExecutor.submit(new AdminTaskThread(client, protocol));
                } else if (SystemConstants.TYPE_READER.equalsIgnoreCase(protocol.getType())) {
                    // 读者操作
                    System.out.println("欢迎读者访问图书管理系统！");
                    System.out.println("您的IP地址是：" + client.getInetAddress().getHostAddress());

                    // 提交读者线程任务到线程池来执行
                    poolExecutor.submit(new ReaderTaskThread(client, protocol));
                }
            } catch (ClassNotFoundException e) {
                System.out.println("有客户端退出！");
            }
        }
    }
}
